package zzj.campus_book_sharing_platform.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;

@Component
@Slf4j
public class CleanFileScheduleTasks {

    @Scheduled(cron = "0/15 * * * * ?")
    public void cleanCache() {
        long currentTime = System.currentTimeMillis();
        long maxAgeMillis =  60 * 1000; // 将天数转换为毫秒
        clean(new File(Constants.filePath).listFiles(), currentTime - maxAgeMillis);
    }

    /**
     * 文件清除
     *
     * @param files
     * @param fileDate
     */
    public static void clean(File[] files, long fileDate) {
        if (files == null) {
            return;
        }

        for (File file : files) {
            try {
                clean(file.listFiles(), fileDate); // 递归处理子目录
                long lastModified = file.lastModified();
                if (lastModified < fileDate) {
                    if (file.delete()) {
                        log.info("文件删除成功: " + file.getAbsolutePath());
                    } else {
                        log.error("文件删除失败: " + file.getAbsolutePath());
                    }
                }
            } catch (Exception e) {
                log.error("定时任务清除文件失败:" + e.getMessage() + "堆栈信息:" + Arrays.toString(e.getStackTrace()));
            }
        }
    }
}
